package shop.servlet;

import java.io.IOException;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import shop.dao.CartDao;
import shop.dao.impl.CartDaoImpl;
import shop.entity.Cart;
import shop.entity.User;
import shop.entity.dto.CartDTO;

@WebServlet("/CartServlet") 
public class CartServlet extends BaseServlet {
	private CartDao dao = new CartDaoImpl();
	
	//把商品加入购物车
	public void add(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		HttpSession session = request.getSession();
		int goodsId = Integer.parseInt(request.getParameter("goodsId"));
		int num = Integer.parseInt(request.getParameter("num"));
		Cart cart = new Cart();
		cart.setGoodsId(goodsId);
		cart.setNum(num);
		User user = (User)session.getAttribute("user");
		cart.setUserId(user.getId());
		List<CartDTO> cartList = dao.findAll(user.getId());
		//当用户往购物车中添加商品时，需要分2种情况：
		//1、购物车中没有该商品，直接添加一条购物车信息
		//2、购物车中存在该商品，修改数量
		boolean flag = false;//flag为true表示购物车存在商品，false表示不存在
		for(CartDTO dto:cartList) {
			if(dto.getGid()==goodsId) {
				flag = true;
				//购物车有该种商品修改数量
				dao.editNum(dto.getId(), num+dto.getNum());
				break;
			}
		}
		if(!flag) {
			//购物车表中没有这个商品进行添加
			dao.add(cart);
		}
	}
	
	//查询用户的购物车列表
	public void findAll(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		HttpSession session = request.getSession();
		User user = (User)session.getAttribute("user");
		List<CartDTO> cartList = dao.findAll(user.getId());
		session.setAttribute("cartList", cartList);
		double totalPrice = 0;
		for(CartDTO dto:cartList) {
			totalPrice += dto.getNum()*dto.getPrice();
		}
		session.setAttribute("totalPrice", totalPrice);
		response.sendRedirect("buyCar.jsp");
	}
	
	//修改购物车商品数量
	public void editNum(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		int id = Integer.parseInt(request.getParameter("id"));
		int num = Integer.parseInt(request.getParameter("num"));
		dao.editNum(id, num);
		findAll(request,response);
	}
	
	
	//删除购物车商品
	public void del(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		HttpSession session = request.getSession();
		User user = (User)session.getAttribute("user");
		int id = Integer.parseInt(request.getParameter("id"));
		String clear = request.getParameter("clear");//清空购物车
		//删除分两种情况：
		if("true".equals(clear)) {
			//2、勾选清空购物车，删除用户所有的购物车商品
			dao.delAll(user.getId());
		}else {
			//1、没有勾选清空购物车，删除单个
			dao.del(id);
		}
		//刷新购物车
		findAll(request,response);
	}
	


}
